<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索和添加 -->
        <div style="margin-top: 15px;">
            <el-input placeholder="请输入内容" v-model="searchUser" class="input-with-select" style="width:300px" @keyup.native.enter='searchUserList'>
                <el-button slot="append" icon="el-icon-search" @click='searchUserList'></el-button>
            </el-input>
            <el-button type="success" plain @click="adddialogFormVisible = true">添加用户</el-button>
        </div>
        <!-- 用户列表静态显示 -->
        <template>
            <el-table :data="userList" style="width: 100%">
                <el-table-column type="index" width='50'>
                </el-table-column>
                <el-table-column prop="username" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="180">
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeUserStatus(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                            <el-button type="primary" icon="el-icon-edit" plain @click="showEditUserList(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                            <el-button type="primary" icon="el-icon-delete" plain @click="showDelectUserList(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="授权角色" placement="top">
                            <el-button type="primary" icon="el-icon-edit" plain @click="accreditUser(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </template>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="adddialogFormVisible">
            <el-form :model="addform" ref='addform' label-width="100px" :rules="rules">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="addform.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addform.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addform.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addform.mobile" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="adddialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserSubmit('addform')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
            <el-form :model="editform" ref='editform' label-width="100px" :rules="rules">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="editform.username" auto-complete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editform.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editform.mobile" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserSubmit('editform')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 授权角色对话框 -->
        <el-dialog title="编辑用户" :visible.sync="accreditdialogFormVisible">
            <el-form :model="accreditform" ref='editform' label-width="100px">
                <el-form-item label="姓名">
                    <el-input v-model="accreditform.username" auto-complete="off" :disabled="true" style="width:150px"></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <template>
                        <el-select v-model="rolesValue" placeholder="请选择" @change="setRoles">
                            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                            </el-option>
                        </el-select>
                    </template>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="accreditdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="accreditUserSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
  getAllUserList,
  addUser,
  editUser,
  delectUser,
  uploadUserStatus, getRolesList, putAccreditUser
} from '@/api/index.js'
export default {
  data () {
    return {
      rolesValue: '',
      rolesList: [],
      value: '',
      userList: [],
      total: 0,
      currentPage: 1,
      pagesize: 10,
      searchUser: '',
      adddialogFormVisible: false,
      editdialogFormVisible: false,
      accreditdialogFormVisible: false,
      //   添加用户
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //   编辑用户h
      editform: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      //   授权角色
      accreditform: {
        username: '',
        id: '',
        rid: ''
      },
      //   添加、编辑用户信息验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur,change'
          }
        ],
        mobile: [{ required: true, message: '电话不能为空' }]
      }
    }
  },
  mounted () {
    this.userListPage()
  },
  methods: {
    //   角色选择时候获取到它选择的角色
    setRoles () {
    //   console.log(this.rolesValue)
      this.accreditform.rid = this.rolesValue
    },
    //   授权角色对话框
    accreditUser (row) {
      console.log(row)
      this.accreditdialogFormVisible = true
      this.accreditform.username = row.username
      this.accreditform.id = row.id
      //   获取角色列表信息
      getRolesList().then(res => {
        console.log(res)
        this.rolesList = res.data
      })
    },
    //   授权角色功能
    accreditUserSubmit () {
      putAccreditUser(this.accreditform).then(res => {
        console.log(res)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          //   如果删除失败，也返回信息
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        this.accreditdialogFormVisible = false
      })
    },
    //   修改用户状态
    changeUserStatus (row) {
      //   console.log(row)
      uploadUserStatus({ id: row.id, status: row.mg_state }).then(res => {
        console.log(res)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          //   如果删除失败，也返回信息
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
      })
    },
    //   删除用户功能
    showDelectUserList (id) {
      this.$confirm(`是否删除id号为${id}的用户?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delectUser(id).then(res => {
            console.log(res)
            //   判断是否删除成功
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
              // 更新页面
              this.userListPage()
            } else {
              //   如果删除失败，也返回信息
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //   弹出编辑用户对话框
    showEditUserList (row) {
      console.log(row)
      this.editdialogFormVisible = true
      this.editform.id = row.id
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
    },
    //   编辑用户功能
    editUserSubmit (editform) {
      this.$refs[editform].validate(valid => {
        if (valid) {
          editUser(this.editform).then(res => {
            console.log(res)
            // 判断创建是否成功
            if (res.meta.status === 200) {
              // 如果成功，返回（弹出）一条正确信息
              this.$message({
                message: '编辑用户成功',
                type: 'success'
              })
              //  关掉对话框
              this.editdialogFormVisible = false
              //  刷新页面
              this.userListPage()
            }
          })
        } else {
          this.$message({
            message: '输入数据不合法',
            type: 'error'
          })
          return false
        }
      })
    },
    // 添加用户功能
    addUserSubmit (addform) {
      this.$refs[addform].validate(valid => {
        if (valid) {
          addUser(this.addform).then(res => {
            console.log(res)
            // 判断创建是否成功
            if (res.meta.status === 201) {
              // 如果成功，返回（弹出）一条正确信息
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
              //   关掉对话框
              this.adddialogFormVisible = false
              //   重置对话框里面的表单
              this.$refs[addform].resetFields()
              //   刷新页面
              this.userListPage()
            }
          })
        } else {
          this.$message({
            message: '输入数据不合法',
            type: 'error'
          })
          return false
        }
      })
    },
    // 搜索功能
    searchUserList () {
      this.userListPage()
    },
    // 获取动态数据
    userListPage () {
      getAllUserList({
        query: this.searchUser,
        pagenum: this.currentPage,
        pagesize: this.pagesize
      }).then(res => {
        console.log(res)
        // console.log(res.data.users)
        this.userList = res.data.users
        this.total = res.data.total
      })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.userListPage()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.userListPage()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  background-color: #F5F5F5;
  height: 45px;
  font-size: 15px;
  padding-left: 10px;
  line-height: 45px;
  margin-bottom: 15px;
}
</style>
